package com.example.boardroom.serial.table.other;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.IBinder;
import android.os.SystemClock;
import android.util.ArrayMap;
import android.util.Log;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ThreadUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.example.boardroom.R;
import com.example.boardroom.serial.table.DAM3200Table;
import com.example.boardroom.serial.table.ModbusRtu.ModBusBean;
import com.example.boardroom.serial.table.manager.DAM3200Manager;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import tp.xmaihh.serialport.SerialHelper;
import tp.xmaihh.serialport.bean.ComBean;
import tp.xmaihh.serialport.utils.ByteUtil;

public class SimpleService extends Service {
    private SerialHelper serialHelper;//串口通信辅助类
    private ArrayMap<String, String> newsFrameList;
    private DAM3200Manager dam3200Manager;

    private int size = 0;
    private int counter = 0;
    private boolean isItTheFirstCycle = true;//是否第一次循环
    private ThreadUtils.SimpleTask<ModBusBean> simpleTask = null;
    @Override
    public void onCreate() {
        super.onCreate();
        initSerialConfig();
    }
    public static final String TAG = "SimpleServicexxx";
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            LogUtils.dTag(TAG, "通知发出");
            createNotificationChannel();
        } else {
            Notification notification = new Notification.Builder(this)
                    .setContentTitle("硬件监测")
                    .setContentText("硬件监测服务运行中ing")
                    .setWhen(System.currentTimeMillis())
                    .setPriority(Notification.PRIORITY_DEFAULT)
                    .setAutoCancel(false)
                    .setOngoing(true)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .build();

            startForeground(1, notification);
            LogUtils.dTag(TAG, "通知失败");
        }
        if (null == simpleTask || simpleTask.isCanceled()) {
            simpleTask = setSimpleTask();
        }
        startQueryThreadPool();
        return super.onStartCommand(intent, flags, startId);
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    private void createNotificationChannel() {
        NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        // 通知渠道的id
        String CHANNEL_ONE_ID = "plant001";
        // 用户可以看到的通知渠道的名字.
        CharSequence name = getString(R.string.channel_name);
//         用户可以看到的通知渠道的描述
        String description = getString(R.string.channel_description);
        int importance = NotificationManager.IMPORTANCE_HIGH;
        NotificationChannel mChannel = new NotificationChannel(CHANNEL_ONE_ID, name, importance);
//         配置通知渠道的属性
        mChannel.setDescription(description);
//         设置通知出现时的闪灯（如果 android 设备支持的话）
        mChannel.enableLights(true);
        mChannel.setLightColor(Color.RED);
//         设置通知出现时的震动（如果 android 设备支持的话）
//        mChannel.enableVibration(true);
//        mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
//         最后在notificationmanager中创建该通知渠道 //
        mNotificationManager.createNotificationChannel(mChannel);

        // 为该通知设置一个id
        int notifyID = 1;
        // 通知渠道的id

        // Create a notification and set the notification channel.
        Notification notification = new Notification.Builder(this)
                .setContentTitle("硬件监测").setContentText("硬件监测服务运行中")
                .setSmallIcon(R.mipmap.ic_launcher)
                .setChannelId(CHANNEL_ONE_ID)
                .build();
        startForeground(notifyID, notification);


//        Notification.Builder builder = new Notification.Builder(this.getApplicationContext())
//                .setContentIntent(PendingIntent.getActivity(this, 0, intent, 0)) // 设置PendingIntent
//                .setSmallIcon(R.mipmap.ic_launcher) // 设置状态栏内的小图标
//                .setContentTitle(getResources().getString(R.string.app_name))
//                .setContentText("硬件监测服务开启") // 设置上下文内容
//                .setWhen(System.currentTimeMillis()); // 设置该通知发生的时间
//
//        String CHANNEL_ONE_ID = "plant001", CHANNEL_ONE_NAME = "plantname001";
////---------------- 新增代码 --------------------------------------
//        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
//            //修改安卓8.1以上系统报错
//            NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ONE_ID, CHANNEL_ONE_NAME, NotificationManager.IMPORTANCE_HIGH);
//            notificationChannel.enableLights(false);//如果使用中的设备支持通知灯，则说明此通知通道是否应显示灯
//            notificationChannel.setShowBadge(false);//是否显示角标
//            notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
//            NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
//            manager.createNotificationChannel(notificationChannel);
//            builder.setChannelId(CHANNEL_ONE_ID);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }





    private ThreadUtils.SimpleTask<ModBusBean> setSimpleTask() {
        return new ThreadUtils.SimpleTask<ModBusBean>() {


            @Override
            public ModBusBean doInBackground() {
                String toHex, keyAt;
                if (!serialHelper.isOpen()) {
                    try {
                        serialHelper.open();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                keyAt = newsFrameList.keyAt(counter);
                toHex = newsFrameList.get(keyAt);
                if (null == toHex) {
                    counter = 0;
                    return new ModBusBean("", "", false);
                }

                serialHelper.sendHex(toHex);

                if (counter > size - 2) {
                    counter = 0;
                } else {
                    counter = counter + 1;
                }

                return new ModBusBean("toHex", "", false);
            }

            @Override
            public void onSuccess(ModBusBean result) {
                LogUtils.dTag("lufei", "执行成功" + result.tableAddress);

            }

            @Override
            public void onFail(Throwable t) {
                super.onFail(t);
                LogUtils.dTag("lufei", "执行失败" + ThreadUtils.isMainThread());
            }

            @Override
            public void onCancel() {
                super.onCancel();
                LogUtils.dTag("lufei", "执行被取消" + ThreadUtils.isMainThread());
            }
        };

    }

    private void initSerialConfig() {
        dam3200Manager = new DAM3200Manager();
        newsFrameList = new ArrayMap<>(12);
        newsFrameList.put("01", dam3200Manager.queryDAM3200());
        size = newsFrameList.size();


        serialHelper = new SerialHelper("/dev/bus/usb/001/0012", 9600) {
            @Override
            protected void onDataReceived(ComBean paramComBean) {
                String toHex = ByteUtil.ByteArrToHex(paramComBean.bRec);
                try {
                    String port = toHex.substring(0, 2);
                    switch (port) {
                        case "01":
                            //全组状态查询发送给逻辑,但是单条命令反馈信息不需要发送给逻辑
                            if ((toHex.length() == 18) || (toHex.startsWith("010104"))) {
                                EventBus.getDefault().postSticky(new UpDataEvent(port, toHex));
//                                DAM3200Table dam3200Table = new DAM3200Table("", toHex);

                            }
                            LogUtils.dTag("lufeimmmx DAM3200:\n", toHex);
                            break;
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        };
        serialHelper.setStickPackageHelper(is -> {
            try {
                int available = is.available();
                if (available > 0) {
                    byte[] buffer = new byte[available];
                    int size = is.read(buffer);
                    if (size > 0) {
                        return buffer;
                    }
                } else {
                    SystemClock.sleep(400);//等待1.5秒
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        });
    }

    /**
     * 启动问询线程池
     */
    private void startQueryThreadPool() {
        ToastUtils.showShort("硬件监测服务开始工作");
        ThreadUtils.executeBySingleAtFixRate(simpleTask, 500, TimeUnit.MILLISECONDS);

    }



    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy");
        if (serialHelper.isOpen()) {
            serialHelper.close();
        }
        if (null != simpleTask) {
            if (!simpleTask.isCanceled()) {
                simpleTask.cancel();
            }
            simpleTask = null;
        }

        ToastUtils.showShort("硬件监测服务已停止");
    }
}
